package com.example.demo_one.fragment

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.example.demo_one.R


class ListFragment : Fragment() {
    // 1. 实现Fragment和Activity通信
    interface OnItemClickListener {
        // 定义点击事件
        fun onItemClick(position: Int)
    }

    // 3. 声明一个变量来保存实现了OnItemClickListener接口的监听器实例
    private var listener: OnItemClickListener? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_list, container, false)
    }

    // 2. 监听Fragment和Activity通信
    // 当当前的Fragment被添加到Activity中时，会调用此方法
    override fun onAttach(context: Context) {
        super.onAttach(context)
        // 判断当前的Activity是否实现了OnItemClickListener接口
        if (context is OnItemClickListener) {
            listener = context
        } else {
            throw ClassCastException("$context must implement OnItemClickListener")
        }
    }

    // 当Fragment从Activity中移除时，会调用此方法
    override fun onDetach() {
        super.onDetach()
        listener = null
    }

    // 4. 在视图创建完毕时, 获取按钮触发点击事件
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        // 获取按钮并添加点击事件
        view.findViewById<View>(R.id.item1).setOnClickListener {
            listener?.onItemClick(1)
        }
        view.findViewById<View>(R.id.item2).setOnClickListener {
            listener?.onItemClick(2)
        }
    }

}